package test.file;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
java.nio.file

*/


public class binaryfilemerge {

	public static String inFileName = "c:\\temp\\test-in.txt";
	public static String outFileName = "c:\\temp\\test-out.txt";

	public static void main(String[] args) {

		String[] files = new String[4];
		files[0] = "c:\\temp\\test-in-1.txt";
		files[1] = "c:\\temp\\test-in-2.txt";
		files[2] = "c:\\temp\\test-in-3.txt";
		files[3] = "c:\\temp\\test-in-4.txt";

		if (merge(files, outFileName)) {
			System.out.println("Merge Complete ");
		} else {
			System.out.println("Merge Failed ");
		}
	}

	public static boolean removeOldFiles(String[] srcfpArray) {

		boolean result = false;

		for (String each : srcfpArray) {
			File file = new File(each);
			if (!file.delete()) {
				System.err.println("Failed to remove src file : " + each);
			}
		}

		return result;
	}

	public static boolean merge(String[] srcfpArray, String destFP) {

		boolean result = false;

		int read = -1; // check flag

		try {
			// Define dest FilePath
			File f = new File(destFP);

			if (f.exists()) {
				System.err.println("Failed to create a new file (A same name file exists): " + destFP);
				return false;
			}

			FileOutputStream fos = null;
			BufferedOutputStream bos = null;
			fos = new FileOutputStream(f);
			bos = new BufferedOutputStream(fos);

			// Read src files / write to output
			for (String each : srcfpArray) {

				File file = new File(each);
				InputStream is;
				is = new FileInputStream(file);
				BufferedInputStream bis = new BufferedInputStream(is);

				byte[] buffer = new byte[1024];
				while ((read = bis.read(buffer, 0, 1024)) != -1)
					bos.write(buffer, 0, read);

				bis.close();
				bos.flush();
			}
			bos.close();
			result = true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			System.out.println("Merge Exception " + e.toString());
		} catch (IOException e) {
			e.printStackTrace();
			System.out.println("Merge Exception " + e.toString());
		} finally {
		}
		return result;
	}
}
